import  multiprocessing, os
from tkinter import *
from tkinter.ttk import *
import tkinter.filedialog

import mvplytool


class GUI():
    def __init__(self, root) -> None:
        self.queue = multiprocessing.Manager().Queue(1000)
        # p = multiprocessing.cpu_count()
        self.pool = multiprocessing.Pool(processes=1)
        self.root = root
        self.model = None
        self.canOperate = True
        self.initGUI()
        self.root.mainloop()

    def initGUI(self):
        '''在这里初始化UI布局'''
        self.root.title('MagicaVoxel ply模型优化工具')
        self.root.geometry('651x382')
        self.root.minsize(300,150)
        self.root.resizable = False

        self.frame0 = Frame(self.root)
        self.button0 = Button(self.frame0, text='导入模型', command=self.loadModel)
        self.button1 = Button(self.frame0, text='优化模型', command=self.optimizeModel)
        self.button2 = Button(self.frame0, text='保存模型', command=self.saveModel)
        self.button3 = Button(self.frame0, text='清空信息', command=self.clearText)

        self.frame1 = Frame(self.root)
        self.progressbar0 = Progressbar(self.frame1)
        self.progressbar1 = Progressbar(self.frame1)
        self.progressbar2 = Progressbar(self.frame1)
        self.text  = Text(self.frame1)

        self.frame0.pack(side='right', fill='y')
        self.button0.pack()
        self.button1.pack()
        self.button2.pack()
        self.button3.pack()
        
        self.frame1.pack(side='right', fill='both', expand=YES)
        self.progressbar1.pack(fill='x', side='bottom')
        self.progressbar0.pack(fill='x', side='bottom')
        self.text.pack(fill='both', expand=YES, side='bottom')
        self.text.configure(state='disable', exportselection=False)

        self.progressbar0['maximum'] = 100
        self.progressbar1['maximum'] = 100
        
        self.insertText('测试')

        self.root.after(100, self.updateUI)


    # button响应函数
    def optimizeModel(self):
        if self.canOperate and self.model!=None and type(self.model)==mvplytool.ob.PlyModel:
            self.canOperate = False
            self.pool.apply_async(mvplytool.mulpOptimiModel,args=(self.queue, self.model))
        else:
            self.insertText('暂无法操作')

    def saveModel(self):
        filename = tkinter.filedialog.asksaveasfilename(title='保存ply模型文件', filetypes=[('ply', '*.ply')],
                                                initialdir = '.')
        if filename != '':
            mvplytool.save(self.model, filename)
            self.insertText('保存成功')
        else:
            self.insertText('路径不存在')

    def loadModel(self):
        self.insertText('获取模型文件路径')
        filename = tkinter.filedialog.askopenfilename(title='选择ply模型文件', filetypes=[('ply', '*.ply')],
                                                initialdir = '.')
        if os.path.exists(filename):
            self.pool.apply_async(mvplytool.mulpLoad,(self.queue, filename))
            self.canOperate = False
            self.insertText(filename)

        else:
            self.insertText('路径不存在')
        print(filename)

    def clearText(self):
        self.text.configure(state='normal')
        self.text.delete('1.0', 'end')
        self.text.configure(state='disable')

    # 功能函数
    def insertText(self, content):
        if content != '':
            if content[-1] != '\n':
                content += '\n'
            self.text.configure(state='normal')
            index = self.text.index(END)
            print(f'{index}\tc={self.text.get(index)}')
            self.text.insert(END, content)
            self.text.configure(state='disable')
            self.text.see(END)

    def updateUI(self):
        s = ''
        while not self.queue.empty():
            result = self.queue.get()
            t = result['type']
            if t == 'msg':
                s += f'{result["content"]}\n'
                continue
            elif t == 'model':
                self.model = result['content']
                s += f'{self.model.info}\n'
                self.canOperate = True
                continue
            elif t == 'progress':
                content = result['content']
                self.progressbar0['value'] = int(content['value'] * 100)
                self.progressbar1['value'] = int(content['allValue'] * 100)
                continue
        if s!= '':
            self.insertText(s)
        self.root.after(200, self.updateUI)


if __name__ == '__main__':
    root = Tk()
    myGUI = GUI(root)


